const express = require('express')
const router = express.Router()
const {getDb, saveDb} = require('../utils/db')

router.get('',async (req,res)=>{
  try {
    const kanbansDB = await getDb("../mock/kanban.json");
    // const kanbans = kanbansDB.filter(kanban => kanban.projectId === +req.query.projectId)
    res.json(kanbansDB)
  } catch (error) {
    res.status(500).json({
      error: error.message,
    });
  }
})

router.post('',async (req,res)=>{
  try {
    const kanban = req.body;
    console.log(req.query);
    if(!kanban.name){
      return res.status(401).json({
        error:'请添加看板名'
      })
    } 
    let kanbansDB = await getDb("../mock/kanban.json");
    let lastkanban = kanbansDB[kanbansDB.length -1]
    if(lastkanban === undefined){
      lastkanban = new Object()
      lastkanban.ownerId = 193361109
    }
    kanban.id = lastkanban.id? lastkanban.id +1 : 1;
    kanban.created = new Date().getTime()
    kanbansDB.push(kanban)

    await saveDb(kanbansDB,"../mock/kanban.json")
    kanbansDB = await getDb("../mock/kanban.json");

    res.status(200).json(kanbansDB)
  } catch (error) {
    res.status(500).json({
      error:error.message
    })
  }
})


router.delete('/:id',async (req,res)=>{
  let kanbansDB =await getDb("../mock/kanban.json")
  const getkanbanInedx = kanbansDB.findIndex(kanban => kanban.id === +req.params.id)
  if(getkanbanInedx ===-1){
    return res.status(402).json('找不到要删除的内容')
  }
  kanbansDB.splice(getkanbanInedx,1)
  await saveDb(kanbansDB,"../mock/kanban.json")
  kanbansDB =await getDb("../mock/kanban.json")
  res.status(200).json(kanbansDB)
})
module.exports = router